package com.techysky.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.techysky.entity.AchievementDistribution;
import com.techysky.entity.DataModule;
import com.techysky.entity.ExamOnTheSpot;
import com.techysky.entity.ExamRecord;
import com.techysky.entity.Paper;
import com.techysky.entity.Question;
import com.techysky.entity.QuestionModel;
import com.techysky.entity.QuestionPaper;
import com.techysky.entity.Questionc;
import com.techysky.entity.User;
import com.techysky.entity.UserAnswerRecord;
import com.techysky.entity.take;
import com.techysky.entity.uAnswerAndChapter;
import com.techysky.repository.DataModuleRepository;
import com.techysky.repository.ExamRecordRepository;
import com.techysky.repository.PaperRepository;
import com.techysky.repository.QuestionRepository;
import com.techysky.repository.UserAnswerRecordRepository;
import com.techysky.service.ExamRecordService;
import com.techysky.service.PaperManagerService;
import com.techysky.service.QuestionService;


@Controller
@RequestMapping("/examReport")
public class ExamRecprdController {
	String cd="createDate";
	String pi="paperId";
	String se="search";
	String nowTime="yyyy-MM-dd HH:mm:ss";
	private static final Log log=LogFactory.getLog(ExamRecprdController.class);
	@Resource
	private QuestionService questionService;
	@Autowired
	private ExamRecordRepository examRecordRepository;
	@Autowired
	private QuestionRepository questionRepository;
	@Autowired
	private UserAnswerRecordRepository userAnswerRecordRepository;
	@Autowired
	private PaperRepository paperRepository;
	@Autowired
	private DataModuleRepository dataModuleRepository;
	@Resource
	private PaperManagerService paperManagerService;
	@Resource
	private ExamRecordService examRecordService;
	@RequiresPermissions("sys:results:del")
	@RequestMapping(value="/delExaminationOnTheSpot")
	@ResponseBody
	public void delExaminationOnTheSpot(String ids) {
		paperManagerService.delExaminationOnTheSpot(ids);
	}
	@RequiresPermissions("sys:results:edit")
	@RequestMapping(value="/editExaminationOnTheSpot")
	public String editExaminationOnTheSpot(String id,Model model) {
		ExamOnTheSpot examOnTheSpot=paperManagerService.findExaminationOnTheSpot(id);
		model.addAttribute("examOnTheSpot", examOnTheSpot);
		return "examinationOnTheSpot-edit";
	}
	@RequestMapping("/examinationOnTheSpot")
	public String examinationOnTheSpot() {
	
		return "examinationOnTheSpot";
	}
	@RequestMapping(value = "/findExaminationOnTheSpot")
	@ResponseBody
	public Object operator(int pageNo, int pageSize,HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo-1, pageSize);
		String search = request.getParameter(se);
		// 查询数据
		Page<ExamOnTheSpot> list=paperManagerService.findExamOnTheSpot(pageable, search);
		return list.getContent();
	}
	@RequiresPermissions("sys:results:add")
	@RequestMapping("/addExaminationOnTheSpot")
	public String addExaminationOnTheSpot(Model model) {
		List<Paper> papers=paperManagerService.findPapersByExamType("现场考试");
		model.addAttribute("papers", papers);
		return "examinationOnTheSpot-add";
	}
	@RequestMapping("/saveExaminationOnTheSpot")
	@ResponseBody
	public void saveExaminationOnTheSpot(HttpServletRequest request) {
		String paperId=request.getParameter(pi);
		Map<String, String[]> map=new HashMap<>(request.getParameterMap());
		map.remove(pi);
		String getSystemTime=new SimpleDateFormat(nowTime).format(new Date()); 
		for (Entry<String, String[]> entry : map.entrySet()) {
			String key=entry.getKey();
			  String[] value = map.get(key); 
			  ExamOnTheSpot examOnTheSpot=new ExamOnTheSpot();
			  examOnTheSpot.setCreateDate(getSystemTime);
			  Paper paper=new Paper();
			  paper.setId(paperId.split("-")[0]);
			  examOnTheSpot.setPaper(paper);
			  examOnTheSpot.setScore(Float.parseFloat(value[0]));
			  User user=new User();
			  user.setId(key);
			  examOnTheSpot.setUser(user);
			 paperManagerService.saveOrUpadte(examOnTheSpot);
		}
		
	}
	@RequestMapping("/updateExaminationOnTheSpot")
	@ResponseBody
	public void updateExaminationOnTheSpot(String paperId,String score) {
		ExamOnTheSpot examOnTheSpot=paperManagerService.findExaminationOnTheSpot(paperId);
		examOnTheSpot.setScore(Float.parseFloat(score));
		paperManagerService.saveOrUpadte(examOnTheSpot);
	}
	@RequestMapping("/findExaminationOnTheSpotUser")
	@ResponseBody
	public List<Object> findExaminationOnTheSpotUser(String paperId) {
		return paperManagerService.findExaminationOnTheSpotUser(paperId);
		
	}
	@RequestMapping("/achievementDistribution")
	@ResponseBody
	public AchievementDistribution achievementDistribution(String paperId) {
		 return examRecordService.achievementDistribution(paperId);
	}
	
	@RequestMapping("/achievementStatistics")
	public String achievementStatistics() {
		return "achievementStatistics";
	}
	@RequestMapping(value = "/findAchievementStatistics")
	@ResponseBody
	public Object findAchievementStatistics(int pageNo, int pageSize,HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo-1, pageSize);
		String search = request.getParameter(se);
		// 查询数据
		List<Paper> list=examRecordService.achievementStatistics(pageable, search);
		return list;
	}
	
	
	@RequestMapping("/wtake")
	public String wtake() {
		
		return "wtake";
	}
	
	@RequestMapping("/take")
	public String take() {
	 
		return "take";
	}
	@RequestMapping("/my-grade")
	public String results() {
		
		return "my-grade";
	}
	@RequestMapping("/report")
	public String report() {
		
		return "report";
	}
	@RequestMapping("/grade-report-export")
	public String gradeReportExport() {
		
		return "grade-report-export";
	}
	@RequestMapping(value = "/paperM/wtake")
	@ResponseBody
	public Object operator1( int pageNo, int pageSize,  HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo-1, pageSize);
		String search = request.getParameter(se);
		// 查询数据
		return grid(request, pageable, search);
	}
	private Object grid(HttpServletRequest request, PageRequest pageable, final String search) {
		return paperRepository.findAll((Root<Paper> root, CriteriaQuery<?> query, CriteriaBuilder cb)->{		
					List<Predicate> predicate = new ArrayList<Predicate>();
					User user=null!=request.getSession().getAttribute("user")?(User)request.getSession().getAttribute("user"):new User();
					List<ExamRecord> examPaper=examRecordRepository.findByUserId(user.getId());
					if(examPaper!=null&&!examPaper.isEmpty()){
	        			for(int i=0;i<examPaper.size();i++){
	        				String pI = examPaper.get(i).getPaper().getId();
        					Path<String> id = root.get("id");
        					if(search!=null&&search.length()>0) { 
    	        			    Path<String> name = root.get("name");
    						    predicate.add(cb.like(name, "%" + search + "%"));
    						    }
        					predicate.add(cb.notEqual(id,pI));	        			
					        query.orderBy(cb.asc(root.get(cd)));}}
					        Predicate[] pre = new Predicate[predicate.size()];
					        return query.where(predicate.toArray(pre)).getRestriction();}, pageable).getContent();
		}
	@RequestMapping(value = "/paperM/my-grade")
	@ResponseBody
	public Object operator11( int pageNo, int pageSize,  HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo-1, pageSize);
		String search = request.getParameter(se);
		// 查询数据
		return grid11(request, pageable, search);
	}
	private Object grid11(HttpServletRequest request, PageRequest pageable, final String search) {
			return examRecordRepository.findAll((Root<ExamRecord> root, CriteriaQuery<?> query, CriteriaBuilder cb)->{
					List<Predicate> predicate = new ArrayList<Predicate>();
					User user=null!=request.getSession().getAttribute("user")?(User)request.getSession().getAttribute("user"):new User();
					Path<String> name = root.get("name");
					Path<String> code = root.get("code");
					Path<String> userId = root.get("userId");
				    if(search!=null&&search.length()>0){
					 Predicate p = cb.and(cb.like(name, "%" + search + "%"),cb.equal(code,"考试试卷"),cb.equal(userId,user.getId()));
						predicate.add(p); }else{
				     Predicate p = cb.and(cb.equal(code,"考试试卷"),cb.equal(userId,user.getId()));
						predicate.add(p); }   	
				    query.orderBy(cb.asc(root.get(cd)));
					Predicate[] pre = new Predicate[predicate.size()];
					return query.where(predicate.toArray(pre)).getRestriction();
				}, pageable).getContent();}
	@RequestMapping(value = "/paperM/report")
	@ResponseBody
	public Object operator12( int pageNo, int pageSize,  HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo-1, pageSize);
		String search = request.getParameter(se);
		// 查询数据
		return grid12( pageable, search);
	}
	private Object grid12(  PageRequest pageable, final String search) {	
			return examRecordRepository.findAll((Root<ExamRecord> root, CriteriaQuery<?> query, CriteriaBuilder cb)->{   
		       	List<Predicate> predicates = new ArrayList<Predicate>();				
		       if (!StringUtils.isEmpty(search)) { 
		    	    predicates.add(cb.like(root.get("name").as(String.class), "%" + search + "%"));
		            predicates.add(cb.equal(root.get("code"),"考试试卷"));
		          }	else{
		        	  predicates.add(cb.equal(root.get("code"),"考试试卷"));
		          }
		       	query.orderBy(cb.asc(root.get(cd)));				
				return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
		        } , pageable).getContent();
		}
	@RequestMapping(value = "/paperM/take")
	@ResponseBody
	public Object operator13( int pageNo, int pageSize,  HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo-1, pageSize);
		String search = request.getParameter(se);
		// 查询数据
		return grid13(request, pageable, search);
	}
private Object grid13(HttpServletRequest request, PageRequest pageable, final String search) {
		return examRecordRepository.findAll((Root<ExamRecord> root, CriteriaQuery<?> query, CriteriaBuilder cb)->{   				
				List<Predicate> predicate = new ArrayList<Predicate>();
				User user=null!=request.getSession().getAttribute("user")?(User)request.getSession().getAttribute("user"):new User();
				Path<String> name = root.get("name");
				Path<String> createUser = root.get("createUser");
				    if(search!=null&&search.length()>0){
					 Predicate p = cb.and(cb.like(name, "%" + search + "%"),cb.equal(createUser,user.getUserName()));
					predicate.add(p);
				    }else{
					 predicate.add(cb.equal(createUser,user.getUserName()));
				    }
				    query.orderBy(cb.asc(root.get(cd)));
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}, pageable).getContent();}
    @RequestMapping(value="/wtake-xq")
	public String wtakeXq(HttpServletRequest request,Model model,String paperId) {
		//先查询试卷
		Paper paper=paperRepository.findOne(paperId);
		User user=null!=request.getSession().getAttribute("user")?(User)request.getSession().getAttribute("user"):new User();		           
	   	List<UserAnswerRecord> userAnswers=userAnswerRecordRepository.findAlluas(paperId,user.getId());
	   	userAnswerRecordRepository.delete(userAnswers);
		if("考试试卷".equals(paper.getExamType())||"现场考试".equals(paper.getExamType())){
			wtakeCs(model, paperId);
	    }else if("练习试卷".equals(paper.getExamType())){
	    	wtakeLx(model, paperId);	    	
	    }
		return "wtake-xq";
	}
  
   private void wtakeLx( Model model, String paperId) {
	   Paper paper=paperRepository.findOne(paperId);
	   List<take> kss= new  ArrayList<>();
		if(!StringUtils.isEmpty(paper.getRadioScore())&&!StringUtils.isEmpty(paper.getRadioCount())){
			take kl=new take();
			String  code="单选题";
			List<Question>  questions=	questionRepository.findSjByOrderCodeASC(paperId,code);
			if(questions!=null){
				kl.setCh(questions);
			}
			kl.setQuestionTypeTitle("单选题");
			kl.setQuestionType(code);
			kss.add(kl);
		}
		if(!StringUtils.isEmpty(paper.getCheckCount())&&!StringUtils.isEmpty(paper.getCheckScore())){
			take kl1=new take();
			String  code="多选题";
			List<Question>  questions=	questionRepository.findSjByOrderCodeASC(paperId,code);
			if(questions!=null){
				kl1.setCh(questions);
			}
			kl1.setQuestionTypeTitle("多选题");
			kl1.setQuestionType(code);
			kss.add(kl1);
		}
		if(!StringUtils.isEmpty(paper.getJudgeCount())&&!StringUtils.isEmpty(paper.getJudgeScore())){
			take kl2=new take();
			String  code="判断题";
			List<Question>  questions=	questionRepository.findSjByOrderCodeASC(paperId,code);
			if(questions!=null){
				kl2.setCh(questions);
			}
			kl2.setQuestionTypeTitle("判断题");
			kl2.setQuestionType(code);
			kss.add(kl2);
		}
		wtakeLx2(paperId);		
		take kl4=new take();
		kl4.setExamName(paper.getName());
		kl4.setPaperId(paper.getId());
		kl4.setTotalTime(paper.getTotalTime());
		kss.add(kl4);
	    model.addAttribute("sj", kss);
 	    model.addAttribute("examType", paper.getExamType());
	}
private void wtakeLx2(String paperId) {
	 Paper paper=paperRepository.findOne(paperId);
	  List<take> kss= new  ArrayList<>();
	if(!StringUtils.isEmpty(paper.getAskCount())&&!StringUtils.isEmpty(paper.getAskScore())){
		take kl3=new take();
		String  code="问答题";
		List<Question>  questions=	questionRepository.findSjByOrderCodeASC(paperId,code);
		if(questions!=null){
			kl3.setCh(questions);
		}
		kl3.setQuestionTypeTitle("问答题");
		kl3.setQuestionType(code);
		kss.add(kl3);
	}
	if(!StringUtils.isEmpty(paper.getFillCount())&&!StringUtils.isEmpty(paper.getFillScore())){
		take kl5=new take();
		String  code="填空题";
		List<Question>  questions=	questionRepository.findSjByOrderCodeASC(paperId,code);
		if(questions!=null){
			kl5.setCh(questions);
		}
		kl5.setQuestionTypeTitle("填空题");
		kl5.setQuestionType(code);
		kss.add(kl5);
	}
}
private void wtakeCs(Model model,String paperId) {
	   Paper paper=paperRepository.findOne(paperId);
	   List<take> kss= new  ArrayList<>();
		float score=0;
		if(!StringUtils.isEmpty(paper.getRadioScore())&&!StringUtils.isEmpty(paper.getRadioCount())){
			take kl=new take();
			String  code="单选题";
			score+=paper.getRadioScore()*paper.getRadioCount();
			List<Question>  questions=	questionRepository.findSjByOrderCodeASC(paperId,code);
			if(questions!=null){
				kl.setCh(questions);
			}
			kl.setQuestionTypeTitle("单选题（每小题"+paper.getRadioScore()+"分，共"+paper.getRadioScore()*paper.getRadioCount()+"分）");
			kl.setQuestionType(code);
			kss.add(kl);
		}
		if(!StringUtils.isEmpty(paper.getCheckCount())&&!StringUtils.isEmpty(paper.getCheckScore())){
			take kl1=new take();
			String  code="多选题";
			score+=paper.getCheckScore()*paper.getCheckCount();
			List<Question>  questions=	questionRepository.findSjByOrderCodeASC(paperId,code);
			if(questions!=null){
				kl1.setCh(questions);
			}
			kl1.setQuestionTypeTitle("多选题（每小题"+paper.getCheckScore()+"分，共"+paper.getCheckScore()*paper.getCheckCount()+"分）");
			kl1.setQuestionType(code);
			kss.add(kl1);
		}
		if(!StringUtils.isEmpty(paper.getJudgeCount())&&!StringUtils.isEmpty(paper.getJudgeScore())){
			take kl2=new take();
			String  code="判断题";
			score+=paper.getJudgeScore()*paper.getJudgeCount();
			List<Question>  questions=	questionRepository.findSjByOrderCodeASC(paperId,code);
			if(questions!=null){
				kl2.setCh(questions);
			}
			kl2.setQuestionTypeTitle("判断题（每小题"+paper.getJudgeScore()+"分，共"+paper.getJudgeScore()*paper.getJudgeCount()+"分）");
			kl2.setQuestionType(code);
			kss.add(kl2);
		}
		if(!StringUtils.isEmpty(paper.getFillCount())&&!StringUtils.isEmpty(paper.getFillScore())){
			take kl5=new take();
			String  code="填空题";
			List<Question>  questions=	questionRepository.findSjByOrderCodeASC(paperId,code);
			if(questions!=null){
				kl5.setCh(questions);
			}
			kl5.setQuestionTypeTitle("填空题（每小题"+paper.getFillScore()+"分，共"+paper.getFillScore()*paper.getFillCount()+"分）");
			kl5.setQuestionType(code);
			kss.add(kl5);
		}
		take kl4=new take();
		kl4.setExamName(paper.getName());
		kl4.setTotalSc(score);
		kl4.setPaperId(paper.getId());
		kl4.setTotalTime(paper.getTotalTime());
		kss.add(kl4);
		paper.setTotalScore(score);
		paperRepository.save(paper);
	    model.addAttribute("sj", kss);
 	    model.addAttribute("examType", paper.getExamType());
 	    model.addAttribute("totalTime", paper.getTotalTime());
 	    model.addAttribute("questionSize", paper.getCheckCount()+paper.getJudgeCount()+paper.getRadioCount()+paper.getFillCount());
	}
@RequestMapping(value="/wtake-xq2")
  	public String wtakexq2(Model model,String paperId) {	  
      	Paper paper=paperRepository.findOne(paperId);        	    
  	    take kl=new take();
  		kl.setExamName(paper.getName());
  		kl.setPaperId(paper.getId());
  	    kl.setTotalTime(paper.getTotalTime()); 
  	    model.addAttribute("SJK", kl);
  	    model.addAttribute("questionSize", paper.getCheckCount()+paper.getJudgeCount()+paper.getRadioCount()+paper.getFillCount());
  		return "wtake-xq2";
  	}
   @RequestMapping(value="/automatic")
 	public String automatic() {	       	
 		return "automatic";
 	} 
   @RequestMapping(value="/afterExam")
	public String afterExam() {	       	
		return "afterExam";
	} 

   @RequestMapping(value="/take-xq2")
	public String showAnswer(HttpServletRequest request,Model model,String paperId,String examId) {
		//先查询试卷
	   Paper paper;
	  if(paperId!=null){
		 paper=paperRepository.findOne(paperId);  
	  }else{
		 paper=examRecordRepository.findOne(examId).getPaper();
	  }
		User user=null!=request.getSession().getAttribute("user")?(User)request.getSession().getAttribute("user"):new User();		           
		if("考试试卷".equals(paper.getExamType())||"现场考试".equals(paper.getExamType())){
		Float userScore=examRecordRepository.findScoreByPaperIdAndUserId(paper.getId(),user.getId());
		model.addAttribute("userScore", userScore);
		model.addAttribute("tg", userScore==null?0:userScore/paper.getTotalScore());
		}
		Iterator<QuestionPaper> questionPapers=paper.getQuestionPaper().iterator();
		List<uAnswerAndChapter> questionList = new ArrayList<uAnswerAndChapter>();
		while(questionPapers.hasNext()){
			  QuestionPaper questionPaper = questionPapers.next();
			  UserAnswerRecord  userAnswerRecord = userAnswerRecordRepository.findByPaperIdAndQuestionIdAndCreateUser(paper.getId(),questionPaper.getQuestion().getId(),user.getId());			  
			  //查询问题章节关联关系表
			  uAnswerAndChapter uAnswerAndChapter=new uAnswerAndChapter();
			  uAnswerAndChapter.setUserAnswerRecord(userAnswerRecord);
			  Collections.sort(questionList,(uAnswerAndChapter o1, uAnswerAndChapter o2)->{
					Long uar1=(long) 0;
					Long uar2=(long) 0;
					if(ObjectUtils.isEmpty(o1.getUserAnswerRecord())){
						 uar1=(long) 0;
					 }else{
						uar1=o1.getUserAnswerRecord().getOrderCode( );
					 }
					if(ObjectUtils.isEmpty(o2.getUserAnswerRecord())){
						 uar2=(long) 0;
					 }else{
						uar2=o2.getUserAnswerRecord().getOrderCode( );
					 }
					return (int) (uar1-uar2);
				});
			  List<DataModule> datamoduleList=new ArrayList<>();
			  List<QuestionModel> qms=questionService.findModelByQuestionId(questionPaper.getQuestion().getId());
				for(int i=0;i<qms.size();i++){
					//查询章节
					DataModule dm = this.dataModuleRepository.findByDmCode(qms.get(i).getModelDmCode());							
					datamoduleList.add(dm);
				}
				uAnswerAndChapter.setChapterList(datamoduleList);
				
				  questionList.add(uAnswerAndChapter);
			  }
		
		 model.addAttribute("questionList", questionList);
		 model.addAttribute("paper", paper);
		return "take-xq";
	}
	 @RequestMapping(value="/question-step")
	   	public String stepShow(Model model,String paperId) {

	   		//先查询试卷
	        List<Question> questions= new ArrayList<Question>();
	 
	        List<Question>  questions0=	questionRepository.findSjByOrderCodeASC(paperId,"单选题");
	       	List<Question>  questions1=	questionRepository.findSjByOrderCodeASC(paperId,"多选题");
	       	List<Question>  questions2=	questionRepository.findSjByOrderCodeASC(paperId,"判断题");
	       	List<Question>  questions3=	questionRepository.findSjByOrderCodeASC(paperId,"问答题");
	    	List<Question>  questions4=	questionRepository.findSjByOrderCodeASC(paperId,"填空题");
	    
	       	questions.addAll(questions0);
	       	questions.addAll(questions1);
	       	questions.addAll(questions2);
	       	questions.addAll(questions3);
	    	questions.addAll(questions4);
	       	model.addAttribute("dan", questions0.size());
	       	model.addAttribute("duo", questions1.size());
	       	model.addAttribute("pan", questions2.size());
	       	model.addAttribute("wen", questions3.size());
	       	model.addAttribute("tian", questions4.size());
	   	    List<Questionc> questionss= new ArrayList<Questionc>();
	        for (Question question : questions) {
	        	Questionc questionc=new  Questionc();
	        	BeanUtils.copyProperties(question, questionc);
	        	questionss.add(questionc);
	        	
			}	   	    
	        if(!questions.isEmpty()){
		  	      model.addAttribute("chKs", questionss);
		  	    }else{
		  	     model.addAttribute("chKs", new Questionc());
		  	    }
	   		return "question-step";
	     	}
	        
	 
	        
	@RequestMapping(value="/saveAnswer",method=RequestMethod.POST)
	@ResponseBody
	public Object saveAnswer(HttpServletRequest request,@ModelAttribute("userAnswerRecord") UserAnswerRecord userAnswerRecord,@ModelAttribute("examRecord") ExamRecord examRecord,String paperId,Float spendTime) {		 		 
		 Map<String, String[]> map=request.getParameterMap();
		 String getSystemTime=new SimpleDateFormat(nowTime).format(new Date());
		 User user=null!=request.getSession().getAttribute("user")?(User)request.getSession().getAttribute("user"):new User();	
		 Paper paper=paperRepository.findOne(paperId);
		 for (Entry<String, String[]> entry : map.entrySet()) {
			 String a="";
			for (String answers : map.get(entry.getKey())) {
				a=a+answers;
			}
			String key=entry.getKey();
			 if("考试试卷".equals(paper.getExamType())&&key.length()>=32){
				 saveCs(request,userAnswerRecord,examRecord,spendTime,paperId,key,a);
		            }else if("练习试卷".equals(paper.getExamType())){
		            	
		            	saveLx(request,userAnswerRecord,examRecord,spendTime,paperId,key,a);		            	
		            }
			 if("paperId".equals(key)){
				 Iterator<QuestionPaper> questionPapers=paper.getQuestionPaper().iterator();
				 while(questionPapers.hasNext()){
					  QuestionPaper questionPaper = questionPapers.next();
					  Question qp=questionPaper.getQuestion();
					  if(map.get(questionPaper.getQuestion().getId())==null){
						    userAnswerRecord.setId(questionPaper.getQuestion().getId());
			            	userAnswerRecord.setOrderCode(questionPaper.getOrderCode());
			            	userAnswerRecord.setUserAnswer("");
			            	userAnswerRecord.setScore((float) 0.0);
				            userAnswerRecord.setAnswer(qp.getAnswer());
				            userAnswerRecord.setContent(qp.getContent());
				            userAnswerRecord.setA(qp.getA());
				            userAnswerRecord.setB(qp.getB());
				            userAnswerRecord.setC(qp.getC());
				            userAnswerRecord.setD(qp.getD());
				            userAnswerRecord.setPaperId(paperId);
				            userAnswerRecord.setCreateDate(getSystemTime);
				            userAnswerRecord.setCreateUser(user.getId());
				            userAnswerRecord.setCode(qp.getCode());
				            userAnswerRecord.setExplain(qp.getExplain());
				            userAnswerRecord.setQuestionId(qp.getId());
						    userAnswerRecordRepository.save(userAnswerRecord);
					  }	
					  
				 }
				 if(map.size()==2){
					  examRecord.setSpendTime(Float.valueOf(spendTime));
				      examRecord.setUserId(user.getId());
				      examRecord.setCreateUser(user.getUserName());
				      examRecord.setName(paper.getName());
				      examRecord.setCreateDate(getSystemTime);
				      examRecord.setScore((float) 0.0);
				      examRecord.setPaper(paper);
			          examRecord.setTotalScore(paper.getTotalScore());
			          examRecord.setCode(paper.getExamType());
			          examRecord.setTotalTime(paper.getTotalTime());
				      examRecordRepository.save(examRecord);
				  }
			 }
			
		 }
		return "take-xq";
	}
	private void saveCs(HttpServletRequest request, UserAnswerRecord userAnswerRecord, ExamRecord examRecord,
			Float spendTime,String paperId,String key,String a){
			String getSystemTime=new SimpleDateFormat(nowTime).format(new Date());
			 User user=null!=request.getSession().getAttribute("user")?(User)request.getSession().getAttribute("user"):new User();
			 Paper paper=paperRepository.findOne(paperId);	
		 Question  question=questionRepository.findOne(key);
     	Long orderCode=userAnswerRecordRepository.findOrderCodeByPaperIdAndQuestionId(paperId,key);
     	String answer=question.getAnswer();
     		float score;
			if(answer.equals(a)&&"单选题".equals(question.getCode())){
	            	userAnswerRecord.setScore(paper.getRadioScore());
	            	score=+paper.getRadioScore();
	            }else if(answer.equals(a)&&"判断题".equals(question.getCode())){
	            	userAnswerRecord.setScore(paper.getJudgeScore());
	            	score=+paper.getJudgeScore();
	            }else if(answer.equals(a)&&"多选题".equals(question.getCode())){
	            	userAnswerRecord.setScore(paper.getCheckScore());
	            	score=+paper.getCheckScore();
	            }else if(answer.equals(a)&&"填空题".equals(question.getCode())){
		            	userAnswerRecord.setScore(paper.getFillScore());
		            	score=+paper.getFillScore();
		        }else{userAnswerRecord.setScore((float) 0.0);
	            	score=+0;
	            	}
     	userAnswerRecord.setOrderCode(orderCode);
         userAnswerRecord.setId(key);
         userAnswerRecord.setAnswer(answer);
         userAnswerRecord.setContent(question.getContent());
         userAnswerRecord.setUserAnswer(a);
         userAnswerRecord.setA(question.getA());
         userAnswerRecord.setB(question.getB());
         userAnswerRecord.setC(question.getC());
         userAnswerRecord.setD(question.getD());
         userAnswerRecord.setPaperId(paperId);
         userAnswerRecord.setCreateDate(getSystemTime);
         userAnswerRecord.setCreateUser(user.getId());
         userAnswerRecord.setCode(question.getCode());
         userAnswerRecord.setExplain(question.getExplain());
         userAnswerRecord.setQuestionId(question.getId());
         userAnswerRecordRepository.saveAndFlush(userAnswerRecord);
         examRecord.setSpendTime(Float.valueOf(spendTime));
         examRecord.setUserId(user.getId());
         examRecord.setCreateUser(user.getUserName());
         examRecord.setName(paper.getName());
         examRecord.setCreateDate(getSystemTime);
         if(examRecord.getScore()!=null){
        	 examRecord.setScore(score+examRecord.getScore());
         }else{
        	 examRecord.setScore(score);
         }
         examRecord.setPaper(paper);
         examRecord.setTotalScore(paper.getTotalScore());
         examRecord.setCode(paper.getExamType());
         examRecord.setTotalTime(paper.getTotalTime());
         if(examRecord.getCode()!=null&&examRecord.getCode()!=""){
			 examRecordRepository.save(examRecord); 
		 }
	}
	private void saveLx(HttpServletRequest request, UserAnswerRecord userAnswerRecord, ExamRecord examRecord,
			Float spendTime,String paperId,String key,String a){
		String getSystemTime=new SimpleDateFormat(nowTime).format(new Date());
		 User user=null!=request.getSession().getAttribute("user")?(User)request.getSession().getAttribute("user"):new User();
		 Paper paper=paperRepository.findOne(paperId);
		if("练习试卷".equals(paper.getExamType())&&key.length()>=32){
	        Question  question=questionRepository.findOne(key);
 	        String questionId=key;
 	        Long orderCode=userAnswerRecordRepository.findOrderCodeByPaperIdAndQuestionId(paperId,questionId);
 	        userAnswerRecord.setOrderCode(orderCode);
            userAnswerRecord.setId(key);
            userAnswerRecord.setAnswer(question.getAnswer());
            userAnswerRecord.setContent(question.getContent());
            userAnswerRecord.setUserAnswer(a);
            userAnswerRecord.setA(question.getA());
            userAnswerRecord.setB(question.getB());
            userAnswerRecord.setC(question.getC());
            userAnswerRecord.setD(question.getD());
            userAnswerRecord.setPaperId(paperId);
            userAnswerRecord.setCreateDate(getSystemTime);
            userAnswerRecord.setCreateUser(user.getId());
            userAnswerRecord.setCode(question.getCode());
            userAnswerRecord.setExplain(question.getExplain());
            userAnswerRecord.setQuestionId(question.getId());
            userAnswerRecordRepository.save(userAnswerRecord);
            examRecord.setUserId(user.getId());
            examRecord.setCreateUser(user.getUserName());
            examRecord.setSpendTime(Float.valueOf(spendTime));
            examRecord.setName(paper.getName());
            examRecord.setCreateDate(getSystemTime);
            examRecord.setCode(paper.getExamType());
            examRecord.setPaper(paper);
            examRecord.setTotalTime(paper.getTotalTime());
	 }
		if(examRecord.getCode()!=null&&examRecord.getCode()!=""){
			 examRecordRepository.save(examRecord); 
		 }
	}
	@RequestMapping("/outExam")
	@ResponseBody
	public void outExam(String dwmc)  {  
		  
        String sheetName =  dwmc+"成绩统计";  
        String titleName =  dwmc+"成绩统计";  
        String fileName = dwmc+"成绩统计";  
        int columnNumber = 6;  
        List<Paper> paper1=paperManagerService.findPapersByExamType("考试试卷");
        int[] columnWidth = { 20, 20, 20,20, 20, 20};  
        String[] columnName = { "试卷名称", "试卷类型", "总成绩" , "人员数量", "平均分", "合格率"};  
        try {
        	export(sheetName, titleName, fileName,  
			        columnNumber, columnWidth, columnName, paper1);
		} catch (Exception e) {
			log.info(e);
		}  
    }  
	int z=0;
    public void export(String sheetName, String titleName,  
            String fileName, int columnNumber, int[] columnWidth,  
            String[] columnName, List paper1){  
            HSSFWorkbook wb = new HSSFWorkbook();  
            HSSFSheet sheet = wb.createSheet(sheetName);  
            for (int i = 0; i < columnNumber; i++)   
            {  
                for (int j = 0; j <= i; j++)   
                {  
                    if (i == j)   
                    {  
                        sheet.setColumnWidth(i, columnWidth[j] * 256); 
                    }  
                }  
            }  
            HSSFRow row1 = sheet.createRow((int) 0);  
            row1.setHeightInPoints(30); 
            HSSFCellStyle style2 = wb.createCellStyle();  
            style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
            style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
            style2.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);  
            style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
            HSSFFont headerFont1 = (HSSFFont) wb.createFont(); 
            headerFont1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); 
            headerFont1.setFontName("黑体"); 
            headerFont1.setFontHeightInPoints((short) 15); 
            style2.setFont(headerFont1); 
  
            HSSFCell cell1 = row1.createCell(0);// 
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0,  
                    columnNumber - 1));  
            cell1.setCellValue(titleName); 
            cell1.setCellStyle(style2);   
            HSSFRow row = sheet.createRow((int) 1);  
            row.setHeightInPoints(20);
            HSSFCellStyle style = wb.createCellStyle();  
            style.setWrapText(true);
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
            style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
            style.setBottomBorderColor(HSSFColor.BLACK.index);  
            style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
            style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
            style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
            style.setBorderTop(HSSFCellStyle.BORDER_THIN);    
            HSSFFont headerFont = (HSSFFont) wb.createFont(); 
            headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            headerFont.setFontName("黑体"); 
            headerFont.setFontHeightInPoints((short) 10); 
            style.setFont(headerFont);   
            for (int i = 0; i < columnNumber; i++)   
            {  
                HSSFCell cell = row.createCell(i);  
                cell.setCellValue(columnName[i]);  
                cell.setCellStyle(style);  
            } 
            
            for (int i = 0; i < paper1.size(); i++) {   
            	Set<ExamRecord> examRecordSet=((Paper) paper1.get(i)).getExamRecord();
                int totalNum1=examRecordSet.size();
                if(totalNum1>0){
                	tjExam(wb, sheet, columnNumber, paper1,i, z);
               	 z++;
               }
            }  
            try { 
            	File file =new File("D:\\techysky\\Downloads");    
            	//如果文件夹不存在则创建    
            	if  (!file .exists()  && !file .isDirectory()) { 
            	    file.mkdirs();    
            	} 
            	String filename = fileName + ".xls";
                FileOutputStream fout = new FileOutputStream("D:\\techysky\\Downloads\\"+filename);  
                wb.write(fout);  
                fout.close();  
            } catch (Exception e) {  
                log.info(e);  
            }  
            
    }
   
	@SuppressWarnings("rawtypes")
	private void tjExam( HSSFWorkbook wb,HSSFSheet sheet, int columnNumber,List paper1,int i,int z) {
		
		HSSFRow row = sheet.createRow( z + 2); 
		  
        HSSFCellStyle zidonghuanhang = wb.createCellStyle();  
        zidonghuanhang.setWrapText(true);
        zidonghuanhang.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); 
        zidonghuanhang.setBottomBorderColor(HSSFColor.BLACK.index);  
        zidonghuanhang.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
        zidonghuanhang.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
        zidonghuanhang.setBorderRight(HSSFCellStyle.BORDER_THIN);  
        zidonghuanhang.setBorderTop(HSSFCellStyle.BORDER_THIN);  
        HSSFCellStyle zidonghuanhang2 = wb.createCellStyle();  
        zidonghuanhang2.setWrapText(true);  
        zidonghuanhang2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
        zidonghuanhang2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        zidonghuanhang2.setBottomBorderColor(HSSFColor.BLACK.index);  
        zidonghuanhang2.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
        zidonghuanhang2.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
        zidonghuanhang2.setBorderRight(HSSFCellStyle.BORDER_THIN);  
        zidonghuanhang2.setBorderTop(HSSFCellStyle.BORDER_THIN);  
        HSSFCell datacell; 
        
           Set<ExamRecord> examRecordSet=((Paper) paper1.get(i)).getExamRecord();
           int totalNum1=examRecordSet.size();
           double hg1=0;//合格的总人数
           float allScore=0;
         //试卷名称
 			String pName="";
 			//试卷类型
 			String pType="";
 			//总分数
 			String pScore="";
 			//人员数量
 			String per="";
 			//平均分数
 			String average="";
 			//合格率
 			String pQrate="";
 			if(totalNum1>0){
 				for (ExamRecord examRecord : examRecordSet) {
 	  				if((examRecord.getScore()/examRecord.getTotalScore())>=0.6){
 	  				  ++hg1;
 	  				}
 	  				allScore =+examRecord.getScore()+allScore;
 	  			}
 	  			pName=((Paper) paper1.get(i)).getName();
 	  			pType=((Paper) paper1.get(i)).getExamType();
 	  			pScore=String.valueOf(((Paper) paper1.get(i)).getTotalScore());
 	  			per=String.valueOf(examRecordSet.size());
 	  			average=String.valueOf(allScore/totalNum1);
 	  			pQrate=String.valueOf((hg1/totalNum1)*100);
 			}
  			String[] ss={pName,pType,pScore ,per,average,pQrate};
       		for (int j = 0; j < columnNumber; j++){
   				datacell = row.createCell(j); 
   				datacell.setCellValue(ss[j]);
   			 datacell.setCellStyle(zidonghuanhang2);
   			}              		
	}  
}

